#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>

#define FIFO1 "pipe1"
#define FIFO2 "pipe2"
#define MAX_BUF 1024

int fd1, fd2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int should_exit = 0;

void *send_message(void *arg)
{
    char buffer[MAX_BUF];
    while (!should_exit)
    {
        printf("进程2: 请输入消息: ");
        fgets(buffer, MAX_BUF, stdin);
        buffer[strcspn(buffer, "\n")] = '\0';

        pthread_mutex_lock(&mutex);
        write(fd2, buffer, strlen(buffer) + 1);
        pthread_mutex_unlock(&mutex);

        if (strcmp(buffer, "quit") == 0)
        {
            should_exit = 1;
        }
    }
    return NULL;
}

void *receive_message(void *arg)
{
    char buffer[MAX_BUF];
    while (!should_exit)
    {
        pthread_mutex_lock(&mutex);
        ssize_t bytes_read = read(fd1, buffer, MAX_BUF);
        pthread_mutex_unlock(&mutex);

        if (bytes_read > 0)
        {
            buffer[bytes_read] = '\0';
            printf("\n进程2: 收到消息: %s\n", buffer);

            if (strcmp(buffer, "quit") == 0)
            {
                should_exit = 1;
            }
        }
        else
        {
            // 检查是否应该退出
            if (should_exit)
            {
                break;
            }
            // 短暂休眠避免疯狂刷屏
            usleep(100000); // 休眠100毫秒
        }
    }
    return NULL;
}

int main()
{
    // 打开管道
    fd1 = open(FIFO1, O_RDONLY | O_NONBLOCK);
    fd2 = open(FIFO2, O_WRONLY);

    pthread_t send_thread, receive_thread;
    pthread_create(&send_thread, NULL, send_message, NULL);
    pthread_create(&receive_thread, NULL, receive_message, NULL);

    pthread_join(send_thread, NULL);
    pthread_join(receive_thread, NULL);

    // 关闭管道
    close(fd1);
    close(fd2);

    return 0;
}